﻿using System;
using System.Data;
using System.Configuration;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using RuleCode.Common;
using System.Reflection;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Xml;

namespace RuleCode.WebControls
{
    //文件都保存在本地
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:RuleQueryTable runat=server></{0}:RuleQueryTable>")]
    public class RuleQueryTable : CompositeControl, INamingContainer
    {
        #region 声明要显示的控件
        DropDownList fieldDropDownList;
        Button comfirmButton;
        ControlCollection ControlList = new ControlCollection(new Control());//动态创建的字段列表
        ControlCollection ControlList2 = new ControlCollection(new Control());//动态创建的字段列表
        private RuleQueryField ruleQueryField; //私有，供动态创建
        private RuleQueryAction ruleQueryAction; //私有，供动态创建
        public Label tableLabel; //显示表的名称

        //public string QueryXmlFilePath = CurrentUser.FilePath + "\\QueryXml";
        //static public string QueryXMLBasePath = "D:\\Snk\\XML\\";
        static public string QueryXMLBasePath = HttpContext.Current.Request.PhysicalApplicationPath+"XML\\";
        #endregion
        #region 构造方法
        public RuleQueryTable()
            : base()
        {
            //设置访问权限
            if (HttpContext.Current != null && HttpContext.Current.Request != null && (HttpContext.Current.Request.Url.Host != "localhost" && HttpContext.Current.Request.Url.Host != "book.cangbaowang.net"))
            {
                HttpContext.Current.Response.End();
                return;
            }

            if (DateTime.Now.Year != 2010)
            {
                HttpContext.Current.Response.End();
                return;
            }    

        }
        protected void comfirmButton_Click(object sender, EventArgs e)
        {

            OnButtonClick(e);//
        }
        /// <summary>
        /// 表的全局XML文件
        /// </summary>
        /// <param name="tablename"></param>
        /// <returns></returns>
        public static string getXMLFileName(string tablename)
        {
            string queryxmlpath = QueryXMLBasePath +  RuleCode.CurrentUtil.CompanyID + "\\"
                        + tablename + "\\";
            if (!Directory.Exists(queryxmlpath))
                Directory.CreateDirectory(queryxmlpath);
            return queryxmlpath;
        }
        /// <summary>
        /// 单个ID的XML文件
        /// </summary>
        /// <param name="tablename"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string getXMLFileName(string tablename,string id)
        {
            string queryxmlpath = QueryXMLBasePath  + RuleCode.CurrentUtil.CompanyID
                    + "\\" + tablename + "__" + id + "\\";
            if (!Directory.Exists(queryxmlpath))
                Directory.CreateDirectory(queryxmlpath);
            return queryxmlpath;
        }


        public string TableName
        {
            get
            {
                if (ViewState["TableName"] != null)
                {
                    return ViewState["TableName"].ToString();
                }
                return "";
            }
            set
            {
                ViewState["TableName"] = value;
            }
        }
        public string FileID
        {
            get
            {
                if (ViewState["FileID"] != null)
                {
                    return ViewState["FileID"].ToString();
                }
                return "";
            }
            set
            {
                ViewState["FileID"] = value;
            }
        }
        public string FileName
        {
            get
            {
                if (ViewState["FileName"] != null)
                {
                    return ViewState["FileName"].ToString();
                }
                return "";
            }
            set
            {
                ViewState["FileName"] = value;
            }
        }
        #endregion
        #region 显示方法
        //撰写
        protected override void CreateChildControls()
        {
            if (TableName == "")
            {
                return;
            }
            queryNameList = new List<string>();
            queryFileNameList = new List<string>();
            this.fieldDropDownList = new DropDownList();
            this.tableLabel = new Label();
            tableLabel.Text = TableName;
            fieldDropDownList.AutoPostBack = true;
            for (int i = 0; i < 16; i++)
            {
                ruleQueryField = new RuleQueryField();
                ruleQueryField.ID = "RuleQueryField" + ruleQueryField.ClientID + i.ToString();
                ruleQueryField.Visible = false;
                ControlList.Add(ruleQueryField);
            }
            for (int i = 0; i < 16; i++)
            {
                ruleQueryAction = new RuleQueryAction();
                ruleQueryAction.ID = "RuleQueryAction" + ruleQueryAction.ClientID + i.ToString();
                ruleQueryAction.Visible = false;
                ControlList2.Add(ruleQueryAction);
            }
            comfirmButton = new Button();
            comfirmButton.Text = "查询";
            comfirmButton.Click += comfirmButton_Click;

            load11();

            Controls.Clear();
            this.Controls.Add(this.fieldDropDownList);
            this.Controls.Add(this.tableLabel);
            this.Controls.Add(this.comfirmButton);
            foreach (RuleQueryField item in ControlList)
            {
                this.Controls.Add(item);
            }
            foreach (RuleQueryAction item in ControlList2)
            {
                this.Controls.Add(item);
            }
            ChildControlsCreated = true;
        }
        private void load11()
        {
            if (TableName == "")
            {
                return;
            }                                                           
            Assembly ass = RuleCode.Common.AssemblyClass.MyAssembly;     
            MainTable = ass.CreateInstance(
                RuleCode.ObjectTree.Util.RootClassNameSpace+".Table." + TableName) as RuleCode.Common.Table;
            loadFromTableID(FileID);
            tableLabel.Text = MainTable.Property.LabelText;
        }
        //布局
        protected override void Render(HtmlTextWriter writer)
        {
            EnsureChildControls();

            AddAttributesToRender(writer);
            if (TableName == "")
            {
                writer.Write("RuleQueryTable");
                return;
            }
            writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding,
                "1", false);

            writer.Write("<div style=\"width:100%;font-size:small;\">");

            writer.Write("<table style =\"width:100%;\">");
            //writer.Write("<tr>");
            //writer.Write("<td style=\"vertical-align:top;width:25%;\">");

            //writer.Write("</td>");
            //writer.Write("<td style=\"vertical-align:top;width:25%;\">");
            //writer.Write("</td>");
            //writer.Write("<td style=\"vertical-align:top;width:25%;text-align:right;\">");
            
            //writer.Write("</td>");
            //writer.Write("</tr>");
            writer.Write("<tr>");
            writer.Write("<td style=\"vertical-align:top;width:25%;\">");
            Int32 _k = 0;
            foreach (RuleQueryField item in ControlList)
            {
                if (item.Visible)
                {
                    _k++;
                }
            }
            Int32 _i = _k - _k / 2;
            Int32 _j = 0;
            foreach (RuleQueryField item in ControlList)
            {
                _j++;
                if (item.Visible && _j <= _i)
                {
                    item.RenderControl(writer);
                }
            }
            writer.Write("</td>");
            writer.Write("<td style=\"vertical-align:top;width:25%;\">");
            _j = 0;
            foreach (RuleQueryField item in ControlList)
            {
                _j++;
                if (item.Visible & _j > _i)
                {
                    item.RenderControl(writer);
                }
            }
            writer.Write("</td>");

            writer.Write("<td style=\"vertical-align:top;width:25%;\">");
            foreach (RuleQueryAction item in ControlList2)
            {
                if (item.Visible && item.FieldName != "")
                {
                    item.RenderControl(writer);
                }
            }
            writer.Write("</td>");
            writer.Write("<td style=\"vertical-align:top;width:25%;\">");
            if (fieldDropDownList.Items.Count > 0)
            {
                fieldDropDownList.RenderControl(writer);
            }
            writer.Write(" <a href=\"\\Public\\FilterSelect.aspx?tablename=" +
                TableName + "&id=" +
                FileID + "\" target=\"_blank\">自定义查询</a> ");
            writer.Write(" <a href=\"\\Public\\FilterEditData.aspx?tablename=" +
                TableName + "&id=" +
                FileID + "\" target=\"_blank\">批修改数据</a> <br/>");
            //tableLabel.RenderControl(writer);
            comfirmButton.RenderControl(writer);


            writer.Write("</td>");
            writer.Write("</tr>");
            writer.Write("</table>");  // Table
            writer.Write("</div>");  // div

        }
        #endregion

        #region 外部方法
        AOTFieldGroup afg;

        /// <summary>
        /// 表，new后直接赋值进来
        /// </summary>
        /// <param name="_t">""表示取表的基本过滤条件，_id不为空，表示独立存储查询方案</param>
        /// <param name="_fieldGroupName"></param>
        public void SetQueryTable(RuleCode.Common.Table _t, string _id)
        {
            TableName = _t.TableName;
            FileID = _id;
        }


        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="_pageindex">从0开始计数</param>
        /// <returns></returns>
        public RuleCode.Common.Table run(Int32 _pageindex)
        {
            if (queryNameList == null)
            {
                CreateChildControls();
            }
            if (MainTable == null)
            {
                load11();
            }
            if (_pageindex < 0)
            {
                _pageindex = 0;
            }

            //loadFromTableID(FileID);
            string filterstring = "";
            string orderstring = "";
            foreach (RuleQueryField item in ControlList)
            {
                if (item.Visible)
                {
                    filterstring += item.SqlFieldString();
                }
            }
            if (FixedRange != "")
            {
                filterstring += " and " + FixedRange;
            }
            filterstring = " 1=1 " + filterstring;
            if (ControlList2.Count > 0)
            {
                orderstring += "";
                string tmporderstring = "";
                bool fst = true;
                foreach (RuleQueryAction item in ControlList2)
                {
                    if (item.FieldName != "")
                    {
                        tmporderstring = "  "+ item.FieldNameControl+" " + item.ActionValueControl + " ";;
                        if (orderstring.IndexOf("  " + item.FieldNameControl + " ") < 0)
                        {
                            if (fst)
                            {
                                fst = false;
                            }
                            else
                            {
                                orderstring += " , ";
                            }
                            orderstring += tmporderstring;
                        }
                    }
                }
                if (orderstring != "")
                {
                    orderstring = " order by " + orderstring;
                }
            }
            MainTable.PageEnabled = true;
            MainTable.FilterString = filterstring;
            MainTable.SortingString = orderstring;
            MainTable.PageSize = PageSize;
            MainTable.Fetch(_pageindex);
            //MainTable = RuleCode.Common.Table.Find(filterstring, orderstring, MainTable.GetType());
            saveToFile();
            return MainTable;
        }
        public RuleCode.Common.Table MainTable;
        public RuleCode.Common.Table DT
        {
            get
            {
                return this.MainTable;
            }
        }
        /// <summary>
        /// 固定的过滤条件
        /// </summary>
        public string FixedRange
        {
            get
            {
                if (ViewState["FixedRange"] != null)
                {
                    return ViewState["FixedRange"].ToString();
                }
                return "";
            }
            set
            {
                ViewState["FixedRange"] = value;
            }
        }
        /// <summary>
        /// Relation产生的动态过滤条件
        /// 默认使用and与其他字符串连接，这里不需要在写and关键词
        /// </summary>
        public string DyRange
        {
            get
            {
                if (ViewState["DyRange"] != null)
                {
                    return ViewState["DyRange"].ToString();
                }
                return "";
            }
            set
            {
                ViewState["DyRange"] = value;
            }
        }
        public Int32 PageSize
        {
            get
            {
                if (ViewState["PageSize"] != null)
                {
                    return zfunction.str2int(ViewState["PageSize"].ToString());
                }
                return 30;
            }
            set
            {
                ViewState["PageSize"] = value;
            }
        }

        #endregion
        #region 内部方法
        private List<string> queryFileNameList;
        /// <summary>
        /// 获取 所有 Query 相关文件所存储的文件名的列表
        /// </summary>
        public List<string> QueryFileNameList
        {
            get { return this.queryFileNameList; }
        }
        protected List<string> queryNameList;
        /// <summary>
        /// Query的名称列表
        /// </summary>
        public List<string> QueryNameList
        {
            get { return this.queryNameList; }
        }
        /// <summary>
        /// 从表中读取默认字段
        /// 优先顺序
        /// 1，AutoLookup字段组
        /// 2，OverView字段组
        /// 3，前3个字段
        /// </summary>
        private void loadFromTable()
        {


            AOTFieldGroup afg = new AOTFieldGroup();
            //foreach (AOTFieldGroup item in MainTable.AOTFieldGroups)
            //{
            //    if (item.Name == "AutoLookup" && item.FieldGroup.Count > 0)
            //    {
            //        afg = item;
            //    }
            //    if (item.Name == "OverView" && item.FieldGroup.Count > 0 && afg.FieldGroup.Count < 1)
            //    {
            //        afg = item;
            //    }
            //}
            Int32 i = 0;
            if (afg.FieldGroup.Count > 0)
            {
                foreach (AOTField item in afg.FieldGroup)
                {
                    if (i >= 16)
                    {
                        break;
                    }
                    TableFieldType tft = (TableFieldType)MainTable[item.FieldName];
                    ruleQueryField = (RuleQueryField)ControlList[i];
                    ruleQueryField.ThisPage = Page;
                    ruleQueryField.FieldName = tft.BaseProperty.Name;
                    if (tft is TString)
                    {
                        ruleQueryField.FieldValue = "";
                    }
                    else
                    {
                        ruleQueryField.FieldValue = "0";
                    }
                    ruleQueryField.FieldAction = ">=";
                    ruleQueryField.TableFieldName = tft.GetType().Name;
                    ruleQueryField.Visible = true;



                    ruleQueryAction = (RuleQueryAction)ControlList2[i];
                    ruleQueryAction.ThisPage = Page;
                    ruleQueryAction.FieldName = tft.BaseProperty.Name;
                    ruleQueryAction.FieldLabel = RuleCode.Common.SystemLanguage.Instance.GetLabel(tft.BaseProperty.Label);
                    ruleQueryAction.TableName = TableName;
                    ruleQueryAction.FieldAction = "ASC";
                    ruleQueryAction.Visible = true;
                    i++;
                }
            }
            else
            {
                if (MainTable.Property.TitleField != "")
                {
                    TableFieldType tft = (TableFieldType)MainTable[MainTable.Property.TitleField];
                    if (tft != null)
                    {
                        ruleQueryField = (RuleQueryField)ControlList[i];
                        ruleQueryField.ThisPage = Page;
                        ruleQueryField.FieldName = tft.BaseProperty.Name;
                        if (tft is TString)
                        {
                            ruleQueryField.FieldValue = "";
                        }
                        else
                        {
                            ruleQueryField.FieldValue = "0";
                        }
                        ruleQueryField.FieldAction = ">=";
                        ruleQueryField.TableFieldName = tft.GetType().Name;
                        ruleQueryField.Visible = true;

                        ruleQueryAction = (RuleQueryAction)ControlList2[1];
                        ruleQueryAction.ThisPage = Page;
                        ruleQueryAction.FieldName = MainTable.Property.TitleField;
                        ruleQueryAction.FieldLabel = RuleCode.Common.SystemLanguage.Instance.GetLabel(tft.BaseProperty.Label); ;
                        ruleQueryAction.TableName = TableName;
                        ruleQueryAction.FieldAction = "ASC";
                        ruleQueryAction.Visible = true;

                        i++;
                    }
                }
                if (MainTable.Property.TitleField2 != "")
                {
                    TableFieldType tft = (TableFieldType)MainTable[MainTable.Property.TitleField2];
                    if (tft != null)
                    {
                        ruleQueryField = (RuleQueryField)ControlList[i];
                        ruleQueryField.ThisPage = Page;
                        ruleQueryField.FieldName = tft.BaseProperty.Name;
                        if (tft is TString)
                        {
                            ruleQueryField.FieldValue = "";
                        }
                        else
                        {
                            ruleQueryField.FieldValue = "0";
                        }
                        ruleQueryField.FieldAction = ">=";
                        ruleQueryField.TableFieldName = tft.GetType().Name;
                        ruleQueryField.Visible = true;
                        i++;
                    }
                }
                ruleQueryAction = (RuleQueryAction)ControlList2[0];
                ruleQueryAction.ThisPage = Page;
                ruleQueryAction.FieldName = "RECID";
                ruleQueryAction.FieldLabel = "RECID";
                ruleQueryAction.TableName = TableName;
                ruleQueryAction.FieldAction = "DESC";
                ruleQueryAction.Visible = true;
                foreach (string item in MainTable.AllFields)
                {
                    if (i >= 4)
                    {
                        break;
                    }
                    if (item == MainTable.Property.TitleField)
                    {
                        break;
                    }
                    if (item != "RECID" && item != "DATAAREAID"
                        && item != MainTable.Property.TitleField
                        && item != MainTable.Property.TitleField2
                        )
                    {
                        TableFieldType tft = (TableFieldType)MainTable[item];
                        ruleQueryField = (RuleQueryField)ControlList[i];
                        ruleQueryField.ThisPage = Page;
                        ruleQueryField.FieldName = tft.BaseProperty.Name;
                        if (tft is TString)
                        {
                            ruleQueryField.FieldValue = "";
                        }
                        else
                        {
                            ruleQueryField.FieldValue = "0";
                        }
                        ruleQueryField.FieldAction = ">=";
                        ruleQueryField.TableFieldName = tft.GetType().Name;
                        ruleQueryField.Visible = true;

                        if (i == 1 && (((RuleQueryAction)ControlList2[i]).Visible == false))
                        {
                            ruleQueryAction = (RuleQueryAction)ControlList2[i + 1];
                            ruleQueryAction.ThisPage = Page;
                            ruleQueryAction.FieldName = tft.BaseProperty.Name;
                            ruleQueryAction.FieldLabel = RuleCode.Common.SystemLanguage.Instance.GetLabel(tft.BaseProperty.Label);
                            ruleQueryAction.TableName = TableName;
                            ruleQueryAction.FieldAction = "ASC";
                            ruleQueryAction.Visible = true;
                        }

                        i++;
                    }
                }
            }
        }
        /// <summary>
        /// 从ID中读取默认数值
        /// 优先顺序：
        /// 1，当前ID的文件
        /// 2，当前Table的文件
        /// 3，loadFromTable()
        /// </summary>
        private void loadFromTableID(string _id)
        {
            //1，当前ID的文件
            string queryxmlpath = QueryXMLBasePath + "\\" + RuleCode.CurrentUtil.CompanyID
                + "\\" + TableName + "__" + _id + "\\";
            queryxmlpath = getXMLFileName(TableName, _id);
            DirectoryInfo dInfo = new DirectoryInfo(queryxmlpath);
            if (dInfo.Exists == false)
            {
                dInfo.Create();
            }
            FileInfo[] fInfos = dInfo.GetFiles("*.xml");
            foreach (FileInfo fInfo in fInfos)
            {
                this.QueryFileNameList.Add(fInfo.FullName);
                this.QueryNameList.Add(fInfo.Name);
            }
            //2，当前Table的文件
            if (QueryNameList.Count < 1)
            {
                queryxmlpath = QueryXMLBasePath + "\\" + RuleCode.CurrentUtil.CompanyID + "\\"
                    + TableName + "\\";
                queryxmlpath = getXMLFileName(TableName);
                dInfo = new DirectoryInfo(queryxmlpath);
                if (dInfo.Exists == false)
                {
                    dInfo.Create();
                }
                fInfos = dInfo.GetFiles("*.xml");
                foreach (FileInfo fInfo in fInfos)
                {
                    this.QueryFileNameList.Add(fInfo.FullName);
                    this.QueryNameList.Add(fInfo.Name);
                }
            }
            //3，loadFromTable()
            if (QueryNameList.Count < 1)
            {
                string fpath = QueryXMLBasePath + "\\" + RuleCode.CurrentUtil.CompanyID + "\\"
                    + TableName + "___" + "rulecode" + "\\default.xml";
                if (File.Exists(fpath))
                {
                    LoadCurXMLFileName(fpath);
                    return;
                }
                loadFromTable();
            }
            else
            {
                fieldDropDownList.Items.Clear();
                foreach (string item in QueryNameList)
                {
                    fieldDropDownList.Items.Add(item);
                }
                if (!Page.IsPostBack)
                {
                    fieldDropDownList.SelectedIndex = 0;
                }
                Int32 selindex = QueryNameList.IndexOf(fieldDropDownList.SelectedValue);
                string selfilename = QueryFileNameList[selindex];
                LoadCurXMLFileName(selfilename);
            }
        }
        /// <summary>
        /// 当前选中的文件名
        /// </summary>
        /// <param name="_filename">绝对路径</param>
        private void LoadCurXMLFileName(string _filename)
        {
            FileName = _filename;
            string selfilename = _filename;
            //读取XML文件
            DataSet dSet = new DataSet();
            if (selfilename != "")
            {
                dSet.ReadXml(selfilename);
                //读取过滤设置表的数据
                Int32 i = 0;
                if (dSet.Tables["RangeDataTable"] != null)
                {
                    foreach (DataRow dRow in dSet.Tables["RangeDataTable"].Rows)
                    {
                        if (i >= 16)
                        {
                            break;
                        }
                        if (dRow["字段名"].ToString() != "")
                        {
                            string tablename = dRow["表名"].ToString();
                            string fieldname = dRow["字段名"].ToString();
                            string action = dRow["过滤操作"].ToString();
                            string rangevalue = dRow["设置的值"].ToString();

                            TableFieldType tft = (TableFieldType)MainTable[fieldname];
                            ruleQueryField = (RuleQueryField)ControlList[i];
                            ruleQueryField.ThisPage = Page;
                            ruleQueryField.FieldName = fieldname;
                            ruleQueryField.FieldValue = rangevalue;
                            ruleQueryField.FieldAction = action;
                            ruleQueryField.TableFieldName = tft.GetType().Name;
                            ruleQueryField.Visible = true;
                            i++;
                        }


                    }
                }
                //读取排序表中的数据
                i = 0;
                if (dSet.Tables["SortingDataTable"] != null)
                {
                    foreach (DataRow dRow in dSet.Tables["SortingDataTable"].Rows)
                    {
                        if (i >= 16)
                        {
                            break;
                        }
                        if (dRow["字段名"].ToString() != "")
                        {
                            string action = dRow["排序方向"].ToString();
                            string tablename = dRow["表名"].ToString();
                            string fieldname = dRow["字段名"].ToString();

                            TableFieldType tft = (TableFieldType)MainTable[fieldname];
                            ruleQueryAction = (RuleQueryAction)ControlList2[i];
                            ruleQueryAction.ThisPage = Page;
                            ruleQueryAction.FieldName = fieldname;
                            ruleQueryAction.FieldLabel = RuleCode.Common.SystemLanguage.Instance.GetLabel(tft.BaseProperty.Label);
                            ruleQueryAction.TableName = tablename;
                            ruleQueryAction.FieldAction = action;
                            ruleQueryAction.Visible = true;
                            i++;
                        }
                    }
                }
            }
        }

        DataTable sortingDataTable;
        DataTable rangeDataTable;
        /// <summary>
        /// 保存内容，内容分用户保存
        /// loadFromTable,单独命名保存，不在下拉条件中
        /// loadFromTableID,按用户与ID来保存
        /// </summary>
        private void saveToFile()
        {
            //创建表
            sortingDataTable = new DataTable();
            sortingDataTable.TableName = "sortingDataTable";
            rangeDataTable = new DataTable();
            rangeDataTable.TableName = "rangeDataTable";
            this.sortingDataTable.Columns.Clear();
            this.sortingDataTable.Columns.Add("ID");
            this.sortingDataTable.Columns["ID"].AllowDBNull = false;
            this.sortingDataTable.Columns["ID"].DataType = typeof(int);
            this.sortingDataTable.Columns.Add("表名");
            this.sortingDataTable.Columns["表名"].AllowDBNull = false;
            this.sortingDataTable.Columns.Add("字段名");
            this.sortingDataTable.Columns["字段名"].AllowDBNull = false;
            this.sortingDataTable.Columns.Add("排序方向");
            this.sortingDataTable.Columns["排序方向"].AllowDBNull = false;

            this.rangeDataTable.Columns.Clear();
            this.rangeDataTable.Columns.Add("ID");
            this.rangeDataTable.Columns["ID"].AllowDBNull = false;
            this.rangeDataTable.Columns["ID"].DataType = typeof(int);
            this.rangeDataTable.Columns.Add("分组");
            this.rangeDataTable.Columns["分组"].AllowDBNull = false;
            this.rangeDataTable.Columns["分组"].DataType = typeof(int);
            this.rangeDataTable.Columns.Add("表名");
            this.rangeDataTable.Columns["表名"].AllowDBNull = false;
            this.rangeDataTable.Columns.Add("字段名");
            this.rangeDataTable.Columns["字段名"].AllowDBNull = false;
            this.rangeDataTable.Columns.Add("过滤操作");
            this.rangeDataTable.Columns["过滤操作"].AllowDBNull = false;
            this.rangeDataTable.Columns.Add("设置的值");
            this.rangeDataTable.Columns["设置的值"].AllowDBNull = false;
            this.rangeDataTable.Columns.Add("设置描述");
            this.rangeDataTable.Columns["设置描述"].AllowDBNull = false;
            Int32 ii = 0;
            //添加内容
            foreach (RuleQueryField item in ControlList)
            {
                if (item.Visible && item.FieldName != "")
                {
                    DataRow dr = rangeDataTable.NewRow();
                    dr["ID"] = ii++;
                    dr["分组"] = 1;
                    dr["表名"] = TableName;
                    dr["字段名"] = item.FieldName;
                    dr["过滤操作"] = item.ActionValueControl;
                    dr["设置的值"] = item.FieldValueControl;
                    dr["设置描述"] = "1";
                    rangeDataTable.Rows.Add(dr);
                }
            }
            foreach (RuleQueryAction item in ControlList2)
            {
                if (item.Visible && item.FieldName != "")
                {
                    DataRow dr = sortingDataTable.NewRow();
                    dr["ID"] = ii++;
                    dr["表名"] = TableName;
                    dr["字段名"] = item.FieldNameControl;
                    dr["排序方向"] = item.ActionValueControl;
                    sortingDataTable.Rows.Add(dr);
                }
            }
            //保存文件
            string path = "";
            if (FileName == "")
            {
                path = QueryXMLBasePath + "\\" + RuleCode.CurrentUtil.CompanyID + "\\"
                    + TableName + "___" + "rulecode" + "\\default.xml";
            }
            else
            {
                path = FileName;
            }
            FileInfo fi = new FileInfo(path);
            DirectoryInfo dInfo = new DirectoryInfo(fi.DirectoryName);
            if (dInfo.Exists == false)
            {
                dInfo.Create();
            }
            DataSet dataSet = new DataSet();
            dataSet.Tables.Clear();
            dataSet.Tables.AddRange(new DataTable[] { this.sortingDataTable, this.rangeDataTable });
            dataSet.WriteXml(path);
        }
        #endregion
        #region
        public delegate void ButtonClickEventHandler(object sender, EventArgs e);//事件所需的委托 

        //当颜色改变时触发事件 
        public event ButtonClickEventHandler ButtonClick;//定义一个ColorChanged事件 

        protected virtual void OnButtonClick(EventArgs e)
        {//事件触发方法 
            if (ButtonClick != null)
            {//判断事件是否为空 
                ButtonClick(this, e);//触发事件 
            }
        }


        #endregion
        //动态条件，固定条件，可以代码增加固定过滤条件

        #region AddByDingyuliang
        public static string SortingDataTableName = "sortingDataTable";
        public static string RangeDataTableName = "rangeDataTable";

        /// <summary>
        /// 创建一个新的空的QueryXML文件
        /// </summary>
        /// <param name="xmlFileName">QueryXml文件名</param>
        public static void CreateNewQueryXmlFile(string xmlFileName)
        {
            if (!File.Exists(xmlFileName))
            {
                FileStream fStream =   File.Create(xmlFileName );
                //创建表
                DataTable sortingDataTable = new DataTable();
                sortingDataTable.TableName = "sortingDataTable";
                DataTable rangeDataTable = new DataTable();
                rangeDataTable.TableName = "rangeDataTable";
                sortingDataTable.Columns.Clear();
                sortingDataTable.Columns.Add("ID");
                sortingDataTable.Columns["ID"].AllowDBNull = false;
                sortingDataTable.Columns["ID"].DataType = typeof(int);
                sortingDataTable.Columns.Add("表名");
                sortingDataTable.Columns["表名"].AllowDBNull = false;
                sortingDataTable.Columns.Add("字段名");
                sortingDataTable.Columns["字段名"].AllowDBNull = false;
                sortingDataTable.Columns.Add("排序方向");
                sortingDataTable.Columns["排序方向"].AllowDBNull = false;

                rangeDataTable.Columns.Clear();
                rangeDataTable.Columns.Add("ID");
                rangeDataTable.Columns["ID"].AllowDBNull = false;
                rangeDataTable.Columns["ID"].DataType = typeof(int);
                rangeDataTable.Columns.Add("分组");
                rangeDataTable.Columns["分组"].AllowDBNull = false;
                rangeDataTable.Columns["分组"].DataType = typeof(int);
                rangeDataTable.Columns.Add("表名");
                rangeDataTable.Columns["表名"].AllowDBNull = false;
                rangeDataTable.Columns.Add("字段名");
                rangeDataTable.Columns["字段名"].AllowDBNull = false;
                rangeDataTable.Columns.Add("过滤操作");
                rangeDataTable.Columns["过滤操作"].AllowDBNull = false;
                rangeDataTable.Columns.Add("设置的值");
                rangeDataTable.Columns["设置的值"].AllowDBNull = false;
                rangeDataTable.Columns.Add("设置描述");
                rangeDataTable.Columns["设置描述"].AllowDBNull = false;

                XmlDocument xmlDoc = new XmlDocument();
                DataSet dSet = new DataSet();
                dSet.Tables.Add(rangeDataTable);
                dSet.Tables.Add(sortingDataTable);
                dSet.WriteXml(fStream);
                fStream.Close();
            }
        }
        public static void CreateNewQueryXmlFile(string xmlFileName, string tablename)
        {
            if (!File.Exists(xmlFileName))
            {
                FileStream fStream = File.Create(xmlFileName);
                //创建表
                DataTable sortingDataTable = new DataTable();
                sortingDataTable.TableName = "sortingDataTable";
                DataTable rangeDataTable = new DataTable();
                rangeDataTable.TableName = "rangeDataTable";
                sortingDataTable.Columns.Clear();
                sortingDataTable.Columns.Add("ID");
                sortingDataTable.Columns["ID"].AllowDBNull = false;
                sortingDataTable.Columns["ID"].DataType = typeof(int);
                sortingDataTable.Columns.Add("表名");
                sortingDataTable.Columns["表名"].AllowDBNull = false;
                sortingDataTable.Columns.Add("字段名");
                sortingDataTable.Columns["字段名"].AllowDBNull = false;
                sortingDataTable.Columns.Add("排序方向");
                sortingDataTable.Columns["排序方向"].AllowDBNull = false;

                rangeDataTable.Columns.Clear();
                rangeDataTable.Columns.Add("ID");
                rangeDataTable.Columns["ID"].AllowDBNull = false;
                rangeDataTable.Columns["ID"].DataType = typeof(int);
                rangeDataTable.Columns.Add("分组");
                rangeDataTable.Columns["分组"].AllowDBNull = false;
                rangeDataTable.Columns["分组"].DataType = typeof(int);
                rangeDataTable.Columns.Add("表名");
                rangeDataTable.Columns["表名"].AllowDBNull = false;
                rangeDataTable.Columns.Add("字段名");
                rangeDataTable.Columns["字段名"].AllowDBNull = false;
                rangeDataTable.Columns.Add("过滤操作");
                rangeDataTable.Columns["过滤操作"].AllowDBNull = false;
                rangeDataTable.Columns.Add("设置的值");
                rangeDataTable.Columns["设置的值"].AllowDBNull = false;
                rangeDataTable.Columns.Add("设置描述");
                rangeDataTable.Columns["设置描述"].AllowDBNull = false;

                DataRow dr;
                Assembly ass = RuleCode.Common.AssemblyClass.MyAssembly;
                RuleCode.Common.Table MainTable = ass.CreateInstance(
                    RuleCode.ObjectTree.Util.RootClassNameSpace + ".Table." + tablename) as RuleCode.Common.Table;
                AOTFieldGroup afg = new AOTFieldGroup();
                foreach (AOTFieldGroup item in MainTable.AOTFieldGroups)
                {
                    if (item.Name == "AutoLookup" && item.FieldGroup.Count > 0)
                    {
                        afg = item;
                    }
                    if (item.Name == "OverView" && item.FieldGroup.Count > 0 && afg.FieldGroup.Count < 1)
                    {
                        afg = item;
                    }
                }
                Int32 ii = 0;
                if (afg.FieldGroup.Count > 0)
                {
                    foreach (AOTField item in afg.FieldGroup)
                    {
                        TableFieldType tft = (TableFieldType)MainTable[MainTable.Property.TitleField];
                        dr = rangeDataTable.NewRow();
                        dr["ID"] = ii++;
                        dr["分组"] = 1;
                        dr["表名"] = tablename;
                        dr["字段名"] = item.FieldName;
                        dr["过滤操作"] = ">=";
                        dr["设置描述"] = "1";
                        if (tft is TString)
                        {
                            dr["设置的值"] = "";
                        }
                        else
                        {
                            dr["设置的值"] = "0";
                        }
                        rangeDataTable.Rows.Add(dr);


                        dr = sortingDataTable.NewRow();
                        dr["ID"] = ii++;
                        dr["表名"] = tablename;
                        dr["字段名"] = item.FieldName;
                        dr["排序方向"] = "ASC";
                        sortingDataTable.Rows.Add(dr);
                    }
                }
                else
                {
                    dr = sortingDataTable.NewRow();
                    dr["ID"] = ii++;
                    dr["表名"] = tablename;
                    dr["字段名"] = "RECID";
                    dr["排序方向"] = "ASC";
                    sortingDataTable.Rows.Add(dr);
                    if (MainTable.Property.TitleField != "")
                    {
                        TableFieldType tft = (TableFieldType)MainTable[MainTable.Property.TitleField];
                        if (tft != null)
                        {
                            dr = rangeDataTable.NewRow();
                            dr["ID"] = ii++;
                            dr["分组"] = 1;
                            dr["表名"] = tablename;
                            dr["字段名"] = MainTable.Property.TitleField;
                            dr["过滤操作"] = ">=";
                            dr["设置描述"] = "1";
                            if (tft is TString)
                            {
                                dr["设置的值"] = "";
                            }
                            else
                            {
                                dr["设置的值"] = "0";
                            }
                            rangeDataTable.Rows.Add(dr);

                            dr = sortingDataTable.NewRow();
                            dr["ID"] = ii++;
                            dr["表名"] = tablename;
                            dr["字段名"] = MainTable.Property.TitleField;
                            dr["排序方向"] = "DESC";
                            sortingDataTable.Rows.Add(dr);
                        }
                    }
                    if (MainTable.Property.TitleField2 != "")
                    {
                        TableFieldType tft = (TableFieldType)MainTable[MainTable.Property.TitleField2];
                        if (tft != null)
                        {
                            dr = rangeDataTable.NewRow();
                            dr["ID"] = ii++;
                            dr["分组"] = 1;
                            dr["表名"] = tablename;
                            dr["字段名"] = MainTable.Property.TitleField2;
                            dr["过滤操作"] = ">=";
                            dr["设置描述"] = "1";
                            if (tft is TString)
                            {
                                dr["设置的值"] = "";
                            }
                            else
                            {
                                dr["设置的值"] = "0";
                            }
                            rangeDataTable.Rows.Add(dr);
                        }
                    }
                    foreach (string item in MainTable.AllFields)
                    {
                        if (rangeDataTable.Rows.Count >= 4)
                        {
                            break;
                        }
                        if (item != "RECID" && item != "DATAAREAID"
                            && item != MainTable.Property.TitleField
                            && item != MainTable.Property.TitleField2
                            )
                        {
                            TableFieldType tft = (TableFieldType)MainTable[item];

                            dr = rangeDataTable.NewRow();
                            dr["ID"] = ii++;
                            dr["分组"] = 1;
                            dr["表名"] = tablename;
                            dr["字段名"] = tft.BaseProperty.Name;
                            dr["过滤操作"] = ">=";
                            dr["设置描述"] = "1";
                            if (tft is TString)
                            {
                                dr["设置的值"] = "";
                            }
                            else
                            {
                                dr["设置的值"] = "0";
                            }
                            rangeDataTable.Rows.Add(dr);

                            if (sortingDataTable.Rows.Count < 3)
                            {
                                dr = sortingDataTable.NewRow();
                                dr["ID"] = ii++;
                                dr["表名"] = tablename;
                                dr["字段名"] = MainTable.Property.TitleField;
                                dr["排序方向"] = "DESC";
                                sortingDataTable.Rows.Add(dr);
                            }
                        }
                    }
                }





                XmlDocument xmlDoc = new XmlDocument();
                DataSet dSet = new DataSet();
                dSet.Tables.Add(rangeDataTable);
                dSet.Tables.Add(sortingDataTable);
                dSet.WriteXml(fStream);
                fStream.Close();
            }
        }
        #endregion
    }
}
